package com.leanin.form.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leanin.form.exception.ExceptionCast;
import com.leanin.form.mapper.LeaninEduFormAdviceMapper;
import com.leanin.form.mapper.LeaninEduFormDeptMapper;
import com.leanin.form.mapper.LeaninEduFormDiseaseMapper;
import com.leanin.form.mapper.LeaninEduFormMapper;
import com.leanin.form.model.*;
import com.leanin.form.model.request.EduFormDTO;
import com.leanin.form.model.request.FormQueryDTO;
import com.leanin.form.model.response.*;
import com.leanin.form.model.response.eduform.EduFormCode;
import com.leanin.form.service.EduFormService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author CPJ.
 * @date 2019/6/17.
 * @time 9:58.
 */
@Service
public class EduFormServiceImpl implements EduFormService {

    private static final Logger LOGGER = LoggerFactory.getLogger(EduFormServiceImpl.class);

    @Autowired
    private LeaninEduFormMapper leaninEduFormMapper;

    @Autowired
    private LeaninEduFormAdviceMapper leaninEduFormAdviceMapper;

    @Autowired
    private LeaninEduFormDeptMapper leaninEduFormDeptMapper;

    @Autowired
    private LeaninEduFormDiseaseMapper leaninEduFormDiseaseMapper;

    private Integer getDownLoadCount(){
        Random random = new Random();
        int count = random.nextInt(50);
        return count + 50 ;
    }

    //判断参数是否合理
    private void checkParam(EduFormDTO eduFormDTO) {
        if (eduFormDTO.getFormName() == null) {//宣教表单名为空
            ExceptionCast.cast(EduFormCode.FORM_NAME_NULL);
        }
        if (eduFormDTO.getFormName().length() > 50){//宣教表单名称  超过 50 字
            ExceptionCast.cast(EduFormCode.FORM_NAME_LENGTH_ERROR);
        }
        if (eduFormDTO.getFormTitle().length() > 150){//宣教表单头  超过 150 字
            ExceptionCast.cast(EduFormCode.FORM_TITLE_LENGTH_ERROR);
        }
        if (eduFormDTO.getFormEnd().length() > 150){//宣教表单名称  超过 150 字
            ExceptionCast.cast(EduFormCode.FORM_END_LENGTH_ERROR);
        }
        if (eduFormDTO.getFormContent() == null) {//表单内容为空
            ExceptionCast.cast(EduFormCode.FORM_CONTENT_NULL);
        }



    }

    //添加表单和科室的关联表
    private void  InsertDept(EduFormDTO eduFormDTO){
        //添加宣教表单关联科室
        List<String> depts = eduFormDTO.getDepts();
        if (depts != null && depts.size() > 0) {//判断宣教科室是否为空
            List<LeaninEduFormDept> params = new ArrayList<>();
            for (String dept : depts) {
                LeaninEduFormDept leaninEduFormDept = new LeaninEduFormDept();
                leaninEduFormDept.setEduFormId(eduFormDTO.getId());
                leaninEduFormDept.setDeptCode(dept);
                params.add(leaninEduFormDept);
            }
            leaninEduFormDeptMapper.insertList(params);
        }
    }
    //添加宣教表单关联疾病
    private void insertDiseases(EduFormDTO eduFormDTO){
        List<String> diseases = eduFormDTO.getDiseases();
        if (diseases != null && diseases.size() > 0) {//判断宣教疾病是否为空
            List<LeaninEduFormDisease> params = new ArrayList<>();
            for (String disease : diseases) {
                LeaninEduFormDisease leaninEduFormDisease = new LeaninEduFormDisease();
                leaninEduFormDisease.setEduFormId(eduFormDTO.getId());
                leaninEduFormDisease.setDiseaseCode(disease);
                params.add(leaninEduFormDisease);
            }
            leaninEduFormDiseaseMapper.insertList(params);
        }
    }
    //添加宣教关联医嘱
    private void insertAdvice(EduFormDTO eduFormDTO){
        List<String> advices = eduFormDTO.getAdvices();
        if (advices != null && advices.size() > 0) {//判断宣教医嘱是否为空
            List<LeaninEduFormAdvice> params = new ArrayList<>();
            for (String advice : advices) {
                LeaninEduFormAdvice leaninEduFormAdvice = new LeaninEduFormAdvice();
                leaninEduFormAdvice.setEduFormId(eduFormDTO.getId());
                leaninEduFormAdvice.setAdviceCode(advice);
                params.add(leaninEduFormAdvice);
            }
            leaninEduFormAdviceMapper.insertList(params);
        }
    }

    @Override
    @Transactional
    public CommonResponseResult addEduForm(EduFormDTO eduFormDTO) {
        LOGGER.info("添加的宣教表单信息:{}", JSON.toJSONString(eduFormDTO));
        //检测参数是否合理
        checkParam(eduFormDTO);
        List<LeaninEduForm> eduForms = leaninEduFormMapper.selectByFormName(eduFormDTO.getFormName());
        if (eduForms.size() > 0) {//宣教表单名重复
            ExceptionCast.cast(EduFormCode.FORM_NAME_REPETITION);
        }
        LeaninEduForm leaninEduForm = new LeaninEduForm();
        eduFormDTO.setFormCreateTime(LocalDate.now());//创建时间
        eduFormDTO.setDownloadCount(getDownLoadCount());//下载次数
        BeanUtils.copyProperties(eduFormDTO, leaninEduForm);
        //添加宣教表单
        leaninEduFormMapper.insertSelective(leaninEduForm);
        eduFormDTO.setId(leaninEduForm.getId());
        //添加宣教表单可是关联表
        InsertDept(eduFormDTO);
//        int i = 1/0;
        //添加宣教表单医嘱关联表
        insertAdvice(eduFormDTO);
        //添加宣教表单疾病关联表
        insertDiseases(eduFormDTO);
        return new CommonResponseResult(CommonCode.SUCCESS, leaninEduForm);
    }

    @Override
    @Transactional
    public ResponseResult updateEduForm(EduFormDTO eduFormDTO) {
        LOGGER.info("修改的宣教表单信息:{}", JSON.toJSONString(eduFormDTO));
        //检测参数是否合理
        checkParam(eduFormDTO);
        if (eduFormDTO.getId() == null) {//ID不存在
            ExceptionCast.cast(EduFormCode.FORM_NOT_EXIST);
        }
        List<LeaninEduForm> eduForms = leaninEduFormMapper.selectByFormName(eduFormDTO.getFormName());
        if (eduForms.size() > 1) {//宣教表单名重复
            ExceptionCast.cast(EduFormCode.FORM_NAME_REPETITION);
        }
        LeaninEduForm eduFormVO = leaninEduFormMapper.selectByPrimaryKey(eduFormDTO.getId());
        if (eduFormVO == null) {
            ExceptionCast.cast(EduFormCode.FORM_NOT_EXIST);
        }
        LeaninEduForm leaninEduForm = new LeaninEduForm();
        BeanUtils.copyProperties(eduFormDTO, leaninEduForm);
        leaninEduForm.setDownloadCount(eduFormVO.getDownloadCount());//下载次数
        leaninEduForm.setFormCreateTime(eduFormVO.getFormCreateTime());//创建时间
        leaninEduForm.setFormBelong(eduFormVO.getFormBelong());
        leaninEduFormMapper.updateByPrimaryKeySelective(leaninEduForm);



        //添加宣教表单可是关联表 先删除后添加
        leaninEduFormDeptMapper.deleteByFormId(eduFormVO.getId());
        InsertDept(eduFormDTO);
//        int i = 1/0;
        //添加宣教表单医嘱关联表 先删除后添加
        leaninEduFormAdviceMapper.deleteByFormId(eduFormVO.getId());
        insertAdvice(eduFormDTO);
        //添加宣教表单疾病关联表 先删除后添加
        leaninEduFormDiseaseMapper.deleteByFormId(eduFormVO.getId());
        insertDiseases(eduFormDTO);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    @Override
    public QueryResponseResult findByParam(FormQueryDTO formQueryDTO) {
        LOGGER.info("条件查询宣教表单:{}",formQueryDTO.toString());
        Integer page = formQueryDTO.getPage();
        if (page == null || page < 1){
            page = 1;
        }
        Integer pageSize = formQueryDTO.getPageSize();
        if (pageSize == null || pageSize < 0){
            pageSize = 10;
        }
        PageHelper.startPage(page,pageSize);
        Page<EduFormVO> leaninEduForms = (Page<EduFormVO>) leaninEduFormMapper.findByParam(formQueryDTO);
        //封装返回参数
        QueryResult<EduFormVO> eduFormQueryResult = new QueryResult<>();
        eduFormQueryResult.setTotal(leaninEduForms.getTotal());
        eduFormQueryResult.setList(leaninEduForms.getResult());
        return new QueryResponseResult(CommonCode.SUCCESS,eduFormQueryResult) ;
    }

    @Override
    public CommonResponseResult findById(Long formId) {
        EduFormVO eduFormVO = leaninEduFormMapper.findById(formId);
        if (eduFormVO == null){//表单不存在
            ExceptionCast.cast(EduFormCode.FORM_NOT_EXIST);
        }
        return new CommonResponseResult(CommonCode.SUCCESS,eduFormVO);
    }

    @Override
    @Transactional
    public ResponseResult addDownLoadCount(Long formId) {
        LeaninEduForm leaninEduForm = leaninEduFormMapper.selectByPrimaryKey(formId);
        if (leaninEduForm == null){//表单不存在
            ExceptionCast.cast(EduFormCode.FORM_NOT_EXIST);
        }
        leaninEduForm.setDownloadCount(leaninEduForm.getDownloadCount()+1);
        leaninEduFormMapper.updateByPrimaryKeySelective(leaninEduForm);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseResult deleteForm(Long formId) {
        LeaninEduForm leaninEduForm = leaninEduFormMapper.selectByPrimaryKey(formId);
        if (leaninEduForm == null){//表单不存在
            ExceptionCast.cast(EduFormCode.FORM_NOT_EXIST);
        }
        leaninEduFormMapper.deleteByPrimaryKey(formId);

        leaninEduFormDeptMapper.deleteByFormId(formId);
        leaninEduFormAdviceMapper.deleteByFormId(formId);
        leaninEduFormDiseaseMapper.deleteByFormId(formId);
        return ResponseResult.SUCCESS();
    }

    @Override
    public QueryResponseResult findByAdvice(Integer page,Integer pageSize,String advice) {
        if (page < 1){
            page = 1;
        }
        if (pageSize < 1){
            pageSize = 10;
        }
        if (advice != null){
            advice = advice.replace(" ", "");
        }
        PageHelper.startPage(page,pageSize);
        Page<LeaninEduForm> adviceEduForm = (Page<LeaninEduForm>) leaninEduFormMapper.findByAdvice(advice);
        QueryResult<LeaninEduForm> eduFormQueryResult = new QueryResult<>();
        eduFormQueryResult.setTotal(adviceEduForm.getTotal());
        eduFormQueryResult.setList(adviceEduForm.getResult());
        return new QueryResponseResult(CommonCode.SUCCESS,eduFormQueryResult);
    }

    @Override
    public QueryResponseResult findByAdviceList(Integer page,Integer pageSize,String advices) {
        if (page < 1){
            page = 1;
        }
        if (pageSize < 1){
            pageSize = 10;
        }
        String[] adviceList = null;
        if (advices != null){
            advices = advices.replace(" ", "");
            adviceList = advices.split(",");
        }
        PageHelper.startPage(page,pageSize);
        Page<LeaninEduForm> adviceEduForm = (Page<LeaninEduForm>) leaninEduFormMapper.findByAdviceList(adviceList);
        QueryResult<LeaninEduForm> eduFormQueryResult = new QueryResult<>();
        eduFormQueryResult.setTotal(adviceEduForm.getTotal());
        eduFormQueryResult.setList(adviceEduForm.getResult());
        return new QueryResponseResult(CommonCode.SUCCESS,eduFormQueryResult);
    }


}
